﻿using System;
using System.IO;
using System.Xml.Serialization;
using Caliburn.Micro;
using Scrabble.Model;

namespace Scrabble.Tasks
{
    public class LoadGameTask : IResult
    {
        public event EventHandler<ResultCompletionEventArgs> Completed;

        public string FileName { get; set; }

        public IGame Game { get; private set; }

        public void Execute(ActionExecutionContext context)
        {
            try
            {
                using (TextReader reader = new StreamReader(FileName))
                {
                    Game = Model.Game.FromStateOfPlay(new XmlSerializer(typeof(StateOfPlay)).Deserialize(reader) as StateOfPlay);
                }

                Completed(this, new ResultCompletionEventArgs());
            }
            catch (Exception exception)
            {
                Completed(this, new ResultCompletionEventArgs { Error = exception });
            }
        }
    }
}